import requests
from bs4 import BeautifulSoup
import traceback
import re
import matplotlib.pyplot as plt
import pandas as pd
import csv
from pyecharts.charts import Bar
from pyecharts import options as opts


headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36'
}
url = 'https://xueqiu.com/service/v5/stock/screener/quote/list?page=1&size=30&order=desc&orderby=percent&order_by=percent&market=CN&type=sh_sz&_=1655202886305'
response = requests.get(url=url, headers=headers)

json_data = response.json()

data_list = json_data['data']['list']
title = ['股票代码', '股票名称', '当前价', '涨跌额', '涨跌幅', '年初至今', '成交量', '成交额', '换手率', '市盈率(TTM)', '股息率', '市值']
all_data = []
for data in data_list:
    insert = [data['symbol'], data['name'], data['current'], data['chg'],
              data['percent'], data['current_year_percent'], data['volume'],
              data['amount'], data['turnover_rate'], data['pe_ttm'],
              data['dividend_yield'], data['market_capital']]
    all_data.append(insert)
print(data)

output_csv = pd.DataFrame(all_data, columns=title)
output_csv.to_csv('./data_qimo.csv', index=None)


data_dfone = pd.read_csv('./data_qimo.csv')
dfone = data_dfone.dropna()
df1 = dfone[['股票名称', '成交量']]
df2 = df1.iloc[:30]
print(df2['股票名称'].values)
print(df2['成交量'].values)
plt.figure(figsize=(15, 6))
plt.tick_params(axis='x', labelsize=10)    # 设置x轴标签大小
plt.xticks(rotation=45)
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.bar(x=df2['股票名称'].values,height=df2['成交量'].values)
plt.title('成交量图表 - Volume chart')
plt.show()

c = (
    Bar()
        .add_xaxis(df2['股票名称'].values.tolist())
        .add_yaxis("股票成交量情况", df2['成交量'].values.tolist())
        .set_global_opts(
        title_opts=opts.TitleOpts(title="成交量图表 - Volume chart"),
        datazoom_opts=opts.DataZoomOpts(),
    )
    .render("data.html")
)


data_dftwo = pd.read_csv('./data_qimo.csv')
dftwo = data_dftwo.dropna()
df1 = dftwo[['股票名称', '年初至今']]
df2 = df1.iloc[:30]
print(df2['股票名称'].values)
print(df2['年初至今'].values)
plt.figure(figsize=(15, 6))
plt.tick_params(axis='x', labelsize=10)    # 设置x轴标签大小
plt.xticks(rotation=45)
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.bar(x=df2['股票名称'].values,height=df2['年初至今'].values)
plt.title('年初至今图表 - current_year_percent chart')
plt.show()

c = (
    Bar()
        .add_xaxis(df2['股票名称'].values.tolist())
        .add_yaxis("股票年初至今情况", df2['年初至今'].values.tolist())
        .set_global_opts(
        title_opts=opts.TitleOpts(title="年初至今图表 - current_year_percent chart"),
        datazoom_opts=opts.DataZoomOpts(),
    )
    .render("data.html")
)

print('数据可视化结果完成,请在当前目录下查找打开 data.html 文件!')

